package xyz.lwm.lazycat.utility.resource;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;

import static xyz.lwm.lazycat.utility.PathUtil.normalizePath;

/**
 * @author lwm
 */
public class FileResource implements Resource {

    private final File file;

    private final String classpath;

    FileResource(File file, String classpath) {
        this.file = file;
        this.classpath = normalizePath(classpath);
    }

    @NotNull
    @Override
    public String getName() {
        return file.getName();
    }

    @NotNull
    @Override
    public String getPath() {
        return file.getPath();
    }

    @NotNull
    @Override
    public Resource get(String name) {
        File f = new File(this.file, name);
        return new FileResource(f, classpath + "/" + name);
    }

    @Override
    public boolean exists() {
        return file.exists();
    }

    @Override
    public boolean isFile() {
        return file.isFile();
    }

    @Override
    public boolean isDir() {
        return file.isDirectory();
    }

    @Override
    public InputStream getInputStream() throws IOException {
        return isDir() ? null : Files.newInputStream(file.toPath());
    }

    @Nullable
    @Override
    public String getClasspath() {
        return classpath;
    }

}